import { User } from '../../models/user'
import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'
import { connectToDatabase } from './../../db/mongo'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)

  // 输入验证
  if (!body.email || !body.password) {
    throw createError({
      statusCode: 400,
      statusMessage: 'EMAIL_PASSWORD_REQUIRED'
    })
  }

  await connectToDatabase()

  // 查询用户
  const user = await User.findOne({ email: body.email })
  if (!user) {
    throw createError({
      statusCode: 401,
      statusMessage: 'INVALID_CREDENTIALS'
    })
  }

  // 验证密码
  const isValid = await bcrypt.compare(body.password, user.passwordHash)
  if (!isValid) {
    throw createError({
      statusCode: 401,
      statusMessage: 'INVALID_CREDENTIALS'
    })
  }

  // 生成JWT
  const token = jwt.sign(
    { userId: user._id },
    useRuntimeConfig().jwtSecret,
    { expiresIn: '8h' }
  )

  return {
    status: 'success',
    data: {
      token,
      user: {
        id: user._id,
        email: user.email,
        emailVerified: user.emailVerified
      }
    }
  }
})